package com.hwl.servicebase.handler;

import com.hwl.commonutils.exception.GuliException;
import com.hwl.commonutils.exception.ParamsException;
import com.hwl.commonutils.result.RespBean;
import com.hwl.commonutils.result.ResultCodeEnum;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author long
 * @since 2021-09-23
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ParamsException.class)
    public RespBean paramsError(ParamsException p) {
        return RespBean.error().message(p.getMsg());
    }

    @ExceptionHandler(GuliException.class)
    public RespBean paramsError(GuliException g) {
        return RespBean.error().message(g.getMessage()).code(g.getCode());
    }

    @ExceptionHandler(ArithmeticException.class)
    public RespBean ArithmeticError(ArithmeticException e) {
        return RespBean.error().message("算数异常");
    }

    @ExceptionHandler(IOException.class)
    public RespBean iOException(IOException e) {
        return RespBean.error().message("IO异常");
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public RespBean httpMessageReadException() {
        return RespBean.setResult(ResultCodeEnum.JSON_PARSE_ERROR);
    }

    @ExceptionHandler(BadSqlGrammarException.class)
    public RespBean badSqlException() {
        return RespBean.setResult(ResultCodeEnum.BAD_SQL_GRAMMAR);
    }

    @ExceptionHandler(SQLException.class)
    public RespBean sqlException(SQLException e) {
        if (e instanceof SQLIntegrityConstraintViolationException) {
            return RespBean.error().message("该数据存在关联数据，操作失败");
        }
        return RespBean.error().message("操作数据库失败");
    }

    @ExceptionHandler(Exception.class)
    public RespBean error(Exception e) {
        return RespBean.error().message(e.getMessage());
    }
}
